use crate::{CODE_ACTIVE_KEY, ICON_PATH};
use std::path::PathBuf;
use std::{env, fs};
use tracing::info;
use winreg::enums::{HKEY_CURRENT_USER, KEY_ALL_ACCESS};
use winreg::RegKey;

pub fn get_temp_path() -> String {
    info!("正在获取当前设备Temp目录.");
    let home_dir = env::var("USERPROFILE").unwrap_or_else(|_| env::var("HOME").unwrap());
    let app_file_name = r"app_code_active_notification.ico";
    let mut app_path = PathBuf::from(home_dir);
    app_path.push("AppData");
    app_path.push("Local");
    app_path.push("Temp");
    info!("设备Temp目录获取成功: {}", &app_path.display());
    app_path.join(app_file_name).display().to_string()
}

pub fn install_app_notification_ico() -> anyhow::Result<()> {
    let app_file_name = r"app_code_active_notification.ico";
    fs::write(app_file_name, ICON_PATH)?;
    fs::copy(app_file_name, &get_temp_path())?;
    fs::remove_file(app_file_name)?;
    Ok(())
}

pub fn register_app_id() -> anyhow::Result<()> {
    info!("进行设置应用通知权限.");
    let hcu = RegKey::predef(HKEY_CURRENT_USER);
    let mut installed = false;
    if let Ok(software) = hcu.open_subkey_with_flags(r"Software\Classes\AppUserModelId", KEY_ALL_ACCESS) {
        for sun_key in software.enum_keys().filter_map(|key| key.ok()) {
            if sun_key.contains(CODE_ACTIVE_KEY) {
                installed = true;
                info!("应用通知权限已设置.");
            }
        }
        if !installed {
            install_app_notification_ico()?;
            if let Ok(active_key) = software.create_subkey(CODE_ACTIVE_KEY) {
                active_key.0.set_value("DisplayName", &"设备激活码管理")?;
                active_key.0.set_value("IconUri", &get_temp_path())?;
                active_key.0.set_value("ShowInSettings", &1u32)?;
                info!("应用通知权限设置成功.");
            }
        }
    }
    Ok(())
}